package nio.application;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * @Desc:   基于 NIO 的非阻塞 socket 服务端
 * @author: cww
 * @DateTime: 2020-02-05 23:51
 */

public class NIOSocketServer {
    public static void main(String[] args) throws Exception {
        System.out.println("服务端启动");
        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        // 异步非阻塞
        serverChannel.configureBlocking(false);
        // 绑定连接
        serverChannel.bind(new InetSocketAddress(7777));
        // 获取选择器
        Selector selector = Selector.open();
        // 将 serverChannel 通道注册到 selector 选择器中，并制定监听接收事件
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);
        // 轮询式获取选择 已准备就绪 事件
        while (selector.select() > 0) {
            // 获取当前选择器所有注册的 选择键（已经就绪的监听事件）
            Iterator<SelectionKey> it = selector.selectedKeys().iterator();
            while (it.hasNext()) {
                // 获取准备就绪的事件
                SelectionKey sk = it.next();
                if (sk.isAcceptable()) {
                    // 若接受新连接就绪，则获取客户端连接
                    SocketChannel socketChannel = serverChannel.accept();
                    // 设置为非阻塞模式
                    socketChannel.configureBlocking(false);
                    // 12.将该通道注册到服务器上
                    socketChannel.register(selector, SelectionKey.OP_READ);
                } else if (sk.isReadable()) {
                    // 13.获取当前选择器"就绪" 状态的通道
                    try {
                        SocketChannel socketChannel = (SocketChannel) sk.channel();
                        ByteBuffer buf = ByteBuffer.allocate(1024);
                        int len = 0;
                        while ((len = socketChannel.read(buf)) > 0) {
                            buf.flip();
                            System.out.println(new String(buf.array(), 0, len));
                            buf.clear();
                        }
                    } catch (IOException e) {
                        System.out.println(e.getMessage());
                        it.remove();
                    }
                }
                it.remove();
            }
        }


    }
}
